﻿#if !LITE

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;

using Excel = Microsoft.Office.Interop.Excel;
using Core = Microsoft.Office.Core;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace iPdf
{
    class XlsConverter: OfficeConverter
    {
        #region Fields
        /// <summary>
        /// The logger
        /// </summary>

        private static Excel.Application excel;
        private static Excel.Workbook workbook;

        #endregion

        #region Properties
        protected override string ApplicationName
        {
            get
            {
                return "Microsoft Excel";
            }
        }
        #endregion

        #region Methods
        protected override void OpenApplication()
        {
            if (excel == null)
            {
                excel = new Excel.ApplicationClass();
                excel.Visible = false;
                excel.DisplayAlerts = false;
            }
        }

        protected override void CloseApplication()
        {
            if (excel != null)
            {
                ((Excel._Application)excel).Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
                excel = null;
            }
        }

        protected override void OpenFile()
        {
            workbook = excel.Workbooks.Open(
                                        workItem.Source, 0, Global.TrueValue, Global.NullObject,
                                        Global.NullObject, Global.NullObject, Global.TrueValue,
                                        Global.NullObject, Global.NullObject, Global.NullObject,
                                        Global.FalseValue, Global.NullObject, Global.FalseValue,
                                        Global.NullObject, Excel.XlCorruptLoad.xlRepairFile
                                            );
            ((Excel._Workbook)workbook).Activate();
        }

        protected override void CloseFile()
        {
            if (workbook != null)
            {
                ((Excel._Workbook)workbook).Close(Global.FalseValue, 
                                        Global.NullObject, Global.NullObject);
                workbook = null;
            }
        }

        protected static bool IsBlankCell(Excel.Range cell)
        {
            if (cell == null || cell.Value2 == null)
            {
                return true;
            }

            return false;
        }

        protected static bool IsBlankSheet(Excel.Worksheet sheet)
        {
            if (sheet == null)
            {
                return true;
            }

            Excel.Range usedRange = sheet.UsedRange;
            if (usedRange.Count == 0)
            {
                return true;
            }

            if (usedRange.Count == 1)
            {
                Excel.Range firstCell = (Excel.Range)usedRange.Cells[1, 1];
                return IsBlankCell(firstCell);
            }

            return false;
        }

        protected static bool IsBlankBook(Excel.Workbook book)
        {
            foreach (Excel.Worksheet sheet in book.Sheets)
            {
                if (!IsBlankSheet(sheet))
                {
                    return false;
                }
            }

            return true;
        }

        protected override void PrintOut()
        {
            Excel.Sheets sheets = workbook.Worksheets;
            ArrayList outlines = new ArrayList();

            FileStream outputStream = Helper.OpenWrite(savedFileName);
            Document document = null;
            PdfCopy copyCat = null; 

            int totalNumOfPages = 0;

            foreach (Excel.Worksheet sheet in sheets)
            {
                if (IsBlankSheet(sheet) == true)
                {
                    continue;
                }

                string fileName = PdfCreatorOption.ChangeAutosaveOptions(Global.PdfExt, Format);
                try
                {
                    PdfCreator.PrintOut(sheet);
                }
                catch
                {
                    continue;
                }

                bool printingSucceeded = PdfCreator.WaitForPrintingToFinish(fileName);
                if (printingSucceeded == false)
                {
                    if (MainForm.ActionCancelled == true)
                    {
                        break;
                    }
                    continue;
                }

                if (copyCat == null)
                {
                    document = new Document();
                    copyCat = new PdfCopy(document, outputStream);
                    document.Open();
                }

                PdfReader reader = new PdfReader(fileName);
                int numOfPages = reader.NumberOfPages;
                try
                {
                    PdfPageRearranger.AddPages(reader, copyCat, fileName);
                }
                catch
                {
                    continue;
                }

                if (workItem.Bookmark)
                {
                    //create bookmark
                    outlines.Add(SharpHelper.CreateBookmarkByPageNo(totalNumOfPages + 1, sheet.Name));
                }

                totalNumOfPages += numOfPages;

                if (MainForm.ActionCancelled == true)
                {
                    break;
                }
            }

            if (totalNumOfPages == 0)
            {
                //it's a empty workbook, we add a informative page to show the information to show this
                document = new Document();
                PdfWriter writer = PdfWriter.GetInstance(document, outputStream);
                document.Open();
                document.Add(new Paragraph("Oops, it seems that the workbook " + workItem.Source +
                                                    " is empty."));
                SharpHelper.ClosePdf(document, writer, outputStream, null, null, true);
                document = null;
                outputStream = null;
                copyCat = null;
            }
            
            if(workItem.Bookmark && copyCat != null &&
                outlines != null && outlines.Count > 0)
            {
                copyCat.ViewerPreferences = PdfWriter.PageModeUseOutlines;
                copyCat.Outlines = outlines;
            }

            SharpHelper.ClosePdf(document, copyCat, outputStream);
            workItem.Bookmark = false;
        }


        #endregion

    }
}


#endif